/**
 *  Copyright(C) 2007 Juri Strumpflohner
 *  All rights reserved
 *
 *  Created: 29.07.2007
*/

package com.aroundj2me.sandbox;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.ImageItem;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemCommandListener;

import com.aroundj2me.utility.ImageLoader;

public class Rating implements CommandListener,ItemCommandListener {
	private ImageItem[] stars;
	
	Command ok = null;
	Command noRate = null;
	
	public Rating(){
		init();
		noRate = new Command("clear rates", Command.SCREEN, 0);
		addStarCommands();
	}
	
	private void addStarCommands(){
		ok = new Command("rate me", Command.OK, 0);
		for(int i=0; i<stars.length; i++){
			stars[i].setItemCommandListener(this);
			stars[i].setDefaultCommand(ok);
		}
	}
	
	private void init(){
		stars = new ImageItem[5];
		stars[0] = new ImageItem(null, ImageLoader.getImage(ImageLoader.STAROFF), ImageItem.LAYOUT_DEFAULT, null);
		stars[1] = new ImageItem(null, ImageLoader.getImage(ImageLoader.STAROFF), ImageItem.LAYOUT_DEFAULT, null);
		stars[2] = new ImageItem(null, ImageLoader.getImage(ImageLoader.STAROFF), ImageItem.LAYOUT_DEFAULT, null);
		stars[3] = new ImageItem(null, ImageLoader.getImage(ImageLoader.STAROFF), ImageItem.LAYOUT_DEFAULT, null);
		stars[4] = new ImageItem(null, ImageLoader.getImage(ImageLoader.STAROFF), ImageItem.LAYOUT_DEFAULT, null);
		stars[0].setLayout(ImageItem.LAYOUT_CENTER);
	}
	
	private void rate(int rate){
		if(rate>5) return;
		
		for(int i=0; i<stars.length; i++){
			if(i<rate)
				stars[i].setImage(ImageLoader.getImage(ImageLoader.STARON));
			else
				stars[i].setImage(ImageLoader.getImage(ImageLoader.STAROFF));
		}
	}

	public void commandAction(Command arg0, Item arg1) {
		if(arg1 == stars[0]){
			rate(1);
		}else if(arg1 == stars[1]){
			rate(2);
		}else if(arg1 == stars[2]){
			rate(3);
		}else if(arg1 == stars[3]){
			rate(4);
		}else if(arg1 == stars[4]){
			rate(5);
		}
	}

	public void commandAction(Command arg0, Displayable arg1) {
		if(arg0 == noRate){
			rate(0);
		}
	}
	
	/**
	 * Returns the user's rating
	 * @return int representing the rating of the user
	 */
	public int getRating(){
		int rating = 0;
		for(int i=0; i<stars.length; i++){
			if(stars[i].getImage() == ImageLoader.getImage(ImageLoader.STARON))
				rating ++;
		}
		return rating;
	}

	public ImageItem[] getStars() {
		return stars;
	}
}
